How to add an enum or enumeration to a class in C++?
How to add an enum or enumeration to a class in C++?
Obviously this is simple, but I keep forgetting one element or other of the syntax (usually the terminating semi-colon) so I thought if I made a post about it, I would never forget again, and if I did, I could look at my post and remember.
There are certain parts to an enum configuration:
- The enum keyword.
- The name of the enumerator. I name this one Items just as an example but it can be named anything you want almost (of course you can’t use C++ keywords).
- The open bracket: {
- The names of the items separated by comas:
item1, item2, item3
Each item has an integer value starting at 0 and incrementing by one. Optionally, you can change a value, and again, ever value thereafter will be +1. So if you want to start at 1 instead of at 0, you would put this:
item1 = 1, item2, item3
If you wanted to count from 1,2,3 and then 7,8,9 you could do this:
item1 = 1, item2, item3, item7 = 7, item8, item9
Also you can change every item by having every item by assigning every item. - The closing bracket: }
- A statement closing semicolon: ;
So the code for your Items enumerator look like this:
enum Items { item1 = 1, item2, item3 };
A basic class is shown here:
class NewObject { public: // Public members and functions NewObject(); ~NewObject(); protected: // Protected members and functions private: // Private members and functions };
So to add an
enum
to you need to decide, is it a public, protected, or private enum? I think it is most common to have public enumerations so that is what my example shows.class NewObject { public: // Public members and functions NewObject(); ~NewObject(); enum Items { item1 = 1, item2, item3 }; protected: // Protected members and functions private: // Private members and functions };
Now you can use the enum on any instantiated class.